package com.chuanke.ckfamily.action.specil;

import com.alibaba.fastjson.JSONArray;
import com.chuanke.ckfamily.action.base.Response;
import com.chuanke.ckfamily.dao.social.model.Family;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.finance.BillService;
import com.chuanke.ckfamily.service.finance.RedPacketService;
import com.chuanke.ckfamily.service.social.FamilyMemberService;
import com.chuanke.ckfamily.service.social.FamilyService;
import com.chuanke.ckfamily.service.user.UserService;
import com.chuanke.ckfamily.service.util.CkServerUtil;
import com.weijie.core.wy.WyHelper;
import com.weijie.core.wy.model.UserGetUInfo;
import com.weijie.core.wy.response.WyUserGetUinfosResponse;
import com.weijie.corel.wy.request.WyUserGetUinfosRequest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/task")
public class TaskController {

    private static final Logger log = LoggerFactory.getLogger(TaskController.class);

    @Autowired
    private FamilyService familyService;

    @Autowired
    private FamilyMemberService familyMemberService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedPacketService redPacketService;

    @Autowired
    private WyService wy;

    @Autowired
    private BillService billService;

    @Autowired
    private CacheService cacheService;

    @RequestMapping("/familyNumFix")
    @ResponseBody
    public Response fixFamilyNum() {
        try {
            familyService.fixFamilyMember();
            return new Response("ok");

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(e);
        }
    }

    @RequestMapping("/member")
    @ResponseBody
    public Response member() {
        try {
            familyMemberService.checkFamilyMember();
            return new Response("ok");

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(e);
        }
    }

    @RequestMapping("/nick_name")
    @ResponseBody
    public Response nick_name(@RequestParam(value = "uid", required = false) Long uid) {
        try {
            List<User> list = userService.findAll();
            for (User user : list) {
                if (!user.hasWyId()) {
                    continue;
                }
                Long id = user.getId();
                String user_no = user.getUser_no();
                String nick_name = user.getNick_name();
                if (uid != null && !uid.equals(id)) {
                    continue;
                }


                WyUserGetUinfosRequest request = new WyUserGetUinfosRequest();
                request.setAccids(JSONArray.toJSONString(Arrays.asList(user_no)));
                WyUserGetUinfosResponse response = WyHelper.execute(request);
                if (response.isSuccess()) {
                    List<UserGetUInfo> uinfos = response.getUinfos();
                    if (uinfos == null || uinfos.isEmpty()) {
                        System.out.println("nick_name==============uinfos.isEmpty=======" + user_no);
                        continue;
                    }

                    UserGetUInfo info = uinfos.get(0);
                    String name = info.getName();
                    if (!nick_name.equals(name)) {
                        System.out.println("nick_name==============!equals=======" + user_no);
                    }
                }
            }

            return new Response("ok");

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(e);
        }
    }


    @RequestMapping("/aaaa")
    @ResponseBody
    public List<Map<String, Object>> aaaa() throws CFException {
        List<Map<String, Object>> result = new ArrayList<>();
        List<User> all = userService.findAll();
        System.out.println(all.size());
        if (all == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        for (User user : all) {
            User loadUser = CkServerUtil.loadUser(user.getId());
            if (loadUser == null) {
                System.out.println("==============================" + user.getId());
                continue;
            }
            if (user.getSuper_id() == null && loadUser.getSuper_id() == null) {
                continue;
            }
            if (user.getSuper_id() != null && loadUser.getSuper_id() != null && user.getSuper_id().equals(loadUser.getSuper_id())) {
                continue;
            }

            Family byOwner = familyService.getByOwner(user.getId());
            if (byOwner != null) {
                Family f = new Family();
                f.setId(byOwner.getId());
                f.setSuper_id(loadUser.getSuper_id());
                familyService.update(f);
            }

            User u = new User();
            u.setId(user.getId());
            u.setSuper_id(loadUser.getSuper_id());
            userService.update(u);

            if (user.hasWyId()) {
                wy.updateUser(loadUser);
            }

            map.put("local", user);
            map.put("load", loadUser);
            result.add(map);
        }

        return result;
    }

    @RequestMapping("/bbb")
    @ResponseBody
    public List<Map<String, Object>> bbb() throws CFException {
        Timestamp time27 = new Timestamp(117, 8, 27, 2, 0, 0, 0);
        Timestamp time26 = new Timestamp(117, 8, 26, 2, 0, 0, 0);
        Timestamp time25 = new Timestamp(117, 8, 25, 2, 0, 0, 0);
        Timestamp time24 = new Timestamp(117, 8, 24, 2, 0, 0, 0);
        Timestamp time23 = new Timestamp(117, 8, 23, 2, 0, 0, 0);
        Timestamp time22 = new Timestamp(117, 8, 22, 2, 0, 0, 0);


        billService.addBill(533600L, 79L, 5, time27, 533809L, "粉丝家族收益");
        billService.addBill(533600L, 61L, 5, time26, 533809L, "粉丝家族收益");
        billService.addBill(533600L, 51L, 5, time25, 533809L, "粉丝家族收益");
        billService.addBill(533600L, 48L, 5, time24, 533809L, "粉丝家族收益");
        billService.addBill(533600L, 54L, 5, time23, 533809L, "粉丝家族收益");
        billService.addBill(533600L, 16L, 5, time22, 533809L, "粉丝家族收益");
        return null;
    }

    @RequestMapping("/get_key")
    @ResponseBody
    public Response getKey(@RequestParam("key") String key) {
        Object keyValue = cacheService.get(key);
        log.info("get key =======> key={}, value={}", key, keyValue);
        return new Response(keyValue);
    }

    @RequestMapping("/update_packet")
    @ResponseBody
    public String updatePacket() {
        log.info("开始修正红包=============>");

        redPacketService.updateFalsePacket();

        return "ok";
    }

    @RequestMapping("/update_packet2")
    @ResponseBody
    public String updatePacket2() {
        log.info("开始修正红包=============>");

        redPacketService.updateFalsePacket2();

        return "ok";
    }

    /**
     * 检查缓存中 获得红包 是否和数据库的获得红包一致。如果获得红包在缓存中还没有同步到数据库中，则执行同步操作
     *
     * @return
     */
    @RequestMapping("/update_packet3")
    @ResponseBody
    public String updatePacket3(@RequestParam("pid") String pid) {
        log.info("开始修正获得红包金额 =============>");

        redPacketService.updateFalsePacket3(pid);

        return "ok";
    }

    @RequestMapping("/deleteToken")
    @ResponseBody
    public String deleteToken(@RequestParam("uid") String uid) {
        log.info("删除用户WyToken =============>uid={}", uid);
        User user = userService.findById(uid);
        if(user != null) {
            return "用户不存在";
        }
        User user1 = new User();
        user1.setId(user.getId());
        user1.setWy_token("");
        userService.update(user1);
        return "ok";
    }
}